package com.fernandomdo.ServiceAdministrator;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.fernandomdo.ServiceAdministrator.Territory.TerritoryListItem;

/**
 * <b>Summary</b>
 * <p>This is an adapter for the territory list, which will extract the needed information from the cursor to put into the list fragment
 * @author fernando_mdo
 *
 */
public class TerritoryListAdapter extends SimpleArrayAdapter<TerritoryListItem> {
	public static final String TAG = "TerritoryListAdapter";
	
	Context context;

	public TerritoryListAdapter(Context context, ArrayList<TerritoryListItem> items) {
		super(context, items);
		this.context = context;
	}

	@Override
	public long getItemId(int position) {
		return mItems.get(position).id;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	   	ViewHolder holder = null;
	   	
		// recycle the view
	   	if(convertView == null) {
            convertView = mInflater.inflate(R.layout.territory_list_item, null);
		}
		else {
			holder = (ViewHolder)convertView.getTag();			
		}

    	// avoid having to call findViewById() so often
        if (holder == null) {
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }
        
        TerritoryListItem item = mItems.get(position);               
        holder.name.setText(item.name);
        holder.name.setTextColor(Color.BLACK);
        
        if(item.status == Territory.NOT_AVAILABLE) {
        	holder.status.setText(context.getResources().getString(R.string.territory_unavailable));
        	holder.status.setTextColor(Color.RED);
        }
        else if (item.status == Territory.AVAILABLE){
        	holder.status.setText(context.getResources().getString(R.string.territory_available));
        	holder.status.setTextColor(Color.GREEN);
        }
        else {
        	holder.status.setText(context.getResources().getString(R.string.no_info));
        }
        
        return convertView;
    }

    static class ViewHolder {
        TextView name;
        TextView status;
        
        public ViewHolder(View base) {
        	name = (TextView)base.findViewById(R.id.territory_item_name);
        	status = (TextView)base.findViewById(R.id.territory_item_status);
        }
    }    
}